<?php
/**
 * tis-tis 安装首页文件
 *
 * @copyright (c)2010 昆明力行软件  保留所有权利。
 * @link http://www.tis-tis.com
 * @Author: XiangJie
 * @version: 1.0.0
 */
require_once '../init.php';

require TIS_ROOT.'/install/internal/smarty_config.php';
require TIS_ROOT.'/internal/common.php';
require TIS_ROOT.'/internal/mysql.class.php';

/*检查相关环境以及可写信息*/
if (PHP_VERSION < '5.0'){
	$links[0] = 'TIS不支持当前的 PHP'.PHP_VERSION.' 环境，请您选用支持 PHP5 的主机，请配置好预装的环境。';
	tisMessage($links);
} else if(!is_writable('../config.php')) {
	$links[0] = "配置文件(config.php)不可写，请将其权限修改为可写！";
	tisMessage($links);
}

$act = isset($_GET['act'])? $_GET['act'] : '';

/*进入安装界面*/
if(!$act){
	$smarty->assign("hostname", "localhost:3306");
	$smarty->assign("dbuser", "root");
	$smarty->assign("password", "");
	$smarty->assign("dbname", "");
	$smarty->assign("dbprefix", "tis_");

	$smarty->assign("admin", "");
	$smarty->assign("adminpw", "");
	$smarty->assign("adminpw2", "");
	$smarty->assign("email", "");

	$smarty->display("index.tpl");
}
if($act == "install"){
	$hostname = $_POST['hostname'];
	$dbuser = $_POST['dbuser'];
	$password = $_POST['password'];
	$dbname = $_POST['dbname'];
	$prefix = $_POST['dbprefix'];

	$admin = $_POST['admin'];
	$adminpw = $_POST['adminpw'];
	$adminpw2 = $_POST['adminpw2'];
	$email = $_POST['email'];

	$conn = @mysql_connect($hostname, $dbuser, $password);
	if (!$conn) {
		$msg = '数据库连接出错，请检查数据库相关信息是否正确！';

		$smarty->assign("msg", $msg);

		$smarty->assign("hostname", $hostname);
		$smarty->assign("dbuser", $dbuser);
		$smarty->assign("password", $password);
		$smarty->assign("dbname", $dbname);
		$smarty->assign("dbprefix", $prefix);

		$smarty->assign("admin", $admin);
		$smarty->assign("adminpw", $adminpw);
		$smarty->assign("adminpw2", $adminpw2);
		$smarty->assign("email", $email);
		$smarty->display("index.tpl");
	} else {
		//初始化数据库信息
		define('DB_HOST',   $hostname);
		define('DB_USER',   $dbuser);
		define('DB_PASSWD', $password);
		define('DB_NAME',   $dbname);
		define('DB_PREFIX', $prefix);

		$result .= create_config_file();
		/*获取相关MySql的实例*/
		$DB = MySql::getInstance();

		$result .= create_table_info();

		$pw = md5($adminpw);
		$result .= insert_admin_values($admin, $pw, $email);

		$result .= "恭喜你 {$admin}，TIS安装成功<br />";
		if (DEL_INSTALLER === 1 && !@unlink('./install.php') || DEL_INSTALLER === 0) {
			$result .= '<span style="color:red;"><b>请删除根目录install安装目录。</b></span> ';
		}

		$result .= '<a href=".././"> 查看首页 </a>';

		$links[0] = $result;

		tisMessage($links);

	}
}

/**
 * 创建配置文件以及写入相关信息。
 *
 * @return 写入结果提示信息的。
 * @author XiangJie
 *
 * */
function create_config_file() {
	global $hostname, $dbuser, $password, $dbname, $prefix;
	$config_info = "<?php\n"
	."//mysql database address\n"
	."define('DB_HOST','$hostname');"
	."\n//mysql database user\n"
	."define('DB_USER','$dbuser');"
	."\n//database password\n"
	."define('DB_PASSWD','$password');"
	."\n//database name\n"
	."define('DB_NAME','$dbname');"
	."\n//database prefix\n"
	."define('DB_PREFIX','$prefix');"
	."\n";

	$fp = @fopen('../config.php', 'w');
	$fw = @fwrite($fp, $config_info);
	if (!$fw)
	{
		$links[0] = "配置文件(config.php)不可写，请将其权限修改为可写！";
		tisMessage($links);
	}else{
		$result="配置文件修改成功<br />";
	}
	fclose($fp);

	return $result;
}
/**
 *
 * 插入管理员信息，这里插入的是最高管理员的相关信息
 *
 * @param string $admin     管理员用户名
 * @param string $adminpw   管理员密码
 * @param string $email     管理员邮箱
 */
function insert_admin_values($admin, $adminpw, $email) {
	global $DB, $prefix;
	$sql = "INSERT INTO ".$prefix."admin_user (`user_name`, `email`, `password`, `role_id`) VALUES ('$admin', '$email', '$adminpw', '0');";
	$ret = $DB->query($sql);
	if($ret) {
		$result = "管理员信心插入成功<br />";
	} else {
		$result = "管理员信心插入失败<br />";
	}

	return $result;
}

/**
 * 创建配置文件以及写入相关信息。
 *
 * @return 写入结果提示信息的。
 * @author XiangJie
 *
 * */
function create_table_info() {
	global $DB, $prefix;
	/* 读取SQL文件 */
	$sql = implode('', file('data/structure.sql'));
	$sql = remove_unuse_info($sql);

	$sql = replace_prefix($sql);

	$array_sql = preg_split("/;[\r\n\t]/", $sql);
	foreach($array_sql as $sql)
	{
		$sql = trim($sql);
		if ($sql)
		{
			if (strstr($sql, 'CREATE TABLE'))
			{
				preg_match('/CREATE TABLE ([^ ]*)/', $sql, $matches);
				$ret = $DB->query($sql);
				if ($ret)
				{
					$result .= '数据库表：'.$matches[1].' 创建成功<br />';
				}
			} else {
				$ret = $DB->query($sql);
			}
		}
	}

	return $result;
}

/**
 * 过滤SQL查询串中的注释。该方法只过滤SQL文件中独占一行或一块的那些注释。
 *
 * @access  public
 * @param   string      $sql        SQL查询串
 * @return  string      返回已过滤掉注释的SQL查询串。
 */
function remove_unuse_info($sql)
{
	/* 删除SQL行注释，行注释不匹配换行符 */
	$sql = preg_replace('/^\s*(?:--|#).*/m', '', $sql);

	/* 删除SQL块注释，匹配换行符，且为非贪婪匹配 */
	$sql = preg_replace('/^\s*\/\*.*?\*\//ms', '', $sql);

	return $sql;
}

/**
 * 替换查询串中数据表的前缀。该方法只对下列查询有效：CREATE TABLE,
 * DROP TABLE, ALTER TABLE, UPDATE, REPLACE INTO, INSERT INTO
 *
 * @access  public
 * @param   string      $sql        SQL查询串
 * @return  string      返回已替换掉前缀的SQL查询串。
 */
function replace_prefix($sql)
{
	global $prefix;
	$keywords = 'CREATE\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?|'
	. 'DROP\s+TABLE(?:\s+IF\s+EXISTS)?|'
	. 'ALTER\s+TABLE|'
	. 'UPDATE|'
	. 'REPLACE\s+INTO|'
	. 'DELETE\s+FROM|'
	. 'INSERT\s+INTO';

	$pattern = '/(' . $keywords . ')(\s*)`?' . 'tis_' . '(\w+)`?(\s*)/i';
	$replacement = '\1\2`' . $prefix . '\3`\4';
	$sql = preg_replace($pattern, $replacement, $sql);

	$pattern = '/(UPDATE.*?WHERE)(\s*)`?' . 'tis_' . '(\w+)`?(\s*\.)/i';
	$replacement = '\1\2`' . $prefix . '\3`\4';
	$sql = preg_replace($pattern, $replacement, $sql);

	return $sql;
}
?>